//
//  ZXLSessionManager.m
//  ZXLSign
//
//  Created by zxl02 on 2020/11/26.
//

#import "ZXLSessionManager.h"
#import "AspectsTool.h"
#import "AFHTTPSessionManager.h"
@implementation ZXLSessionManager
-(void)setSecurityHeader{
//    NSString *reqUUID = [[ZXLNetMixAlgorithm sharedInstance] createReqUUID];
//     NSString *aesKey = [[ZXLNetMixAlgorithm sharedInstance] createRandomlyGenerated16BitStringWithReqUUID:reqUUID];
//     NSString *aesKeyEncry = [[ZXLNetMixAlgorithm sharedInstance] encryAESKey:aesKey];
//     [self.requestSerializer setValue:reqUUID forHTTPHeaderField:@"req-uuid"];
//     [self.requestSerializer setValue:aesKeyEncry forHTTPHeaderField:@"req-key"];
//     [self.requestSerializer setValue:@"true" forHTTPHeaderField:@"encryption"];
}
-(NSArray*)setSecurityHeaderWithPost{
    NSMutableArray *dataArray = [NSMutableArray arrayWithCapacity:2];
//    NSString *reqUUID = [[ZXLNetMixAlgorithm sharedInstance] createReqUUID];
//    NSString *aesKey = [[ZXLNetMixAlgorithm sharedInstance] createRandomlyGenerated16BitStringWithReqUUID:reqUUID];
//    NSString *aesKeyEncry = [[ZXLNetMixAlgorithm sharedInstance] encryAESKey:aesKey];
//    [manage.requestSerializer setValue:reqUUID forHTTPHeaderField:@"req-uuid"];
//    [manage.requestSerializer setValue:aesKeyEncry forHTTPHeaderField:@"req-key"];
//    [manage.requestSerializer setValue:@"true" forHTTPHeaderField:@"encryption"];
//    parameters = [[ZXLNetMixAlgorithm sharedInstance] encryParams:parameters andAesKey:aesKey];
//
//    [dataArray addObject:parameters];
//    [dataArray addObject:manager];
    
    return [dataArray copy];
}
-(void)addsign{
//    AFHTTPSessionManager * m =[AFHTTPSessionManager new];
    [AspectsTool zxl_AspectsWithMetalClass:self.superclass Selector:@selector(dataTaskWithHTTPMethod:URLString:parameters:headers:uploadProgress:downloadProgress:success:failure:) Options:ZXLAspectPositionBefore UsingBlock:^(AspectsTool * _Nonnull info, NSError * _Nonnull error) {
        NSLog(@"\n实例方法:instance == %@\narguments == %@", NSStringFromClass([info.zxl_instance class]),info.zxl_arguments);
        NSMutableURLRequest *request =[[NSString stringWithFormat:@"%@", info.zxl_arguments.firstObject] isEqualToString:@"GET"]? [[AFHTTPRequestSerializer  serializer] requestWithMethod:[NSString stringWithFormat:@"%@", info.zxl_arguments.firstObject] URLString:info.zxl_arguments[1] parameters:info.zxl_arguments[2] error:nil]:[[AFJSONRequestSerializer  serializer] requestWithMethod:[NSString stringWithFormat:@"%@", info.zxl_arguments.firstObject] URLString:info.zxl_arguments[1] parameters:info.zxl_arguments[2] error:nil];
            
    }];
    
//    [AspectsTool zxl_AspectsWithClassName:@"AFHTTPSessionManager" Selector:@selector(dataTaskWithHTTPMethod:URLString:parameters:headers:uploadProgress:downloadProgress:success:failure:) Options:ZXLAspectPositionBefore UsingBlock:^(AspectsTool * _Nonnull info, NSError * _Nonnull error) {
//
//        [self.requestSerializer setValue:@"" forHTTPHeaderField:@""];
//
//         NSLog(@"appdelegate在走的类方法:instance == %@\narguments == %@\n", NSStringFromClass([info.zxl_instance class]),info.zxl_arguments);
//
//     }];
//
    
//    [self.requestSerializer setValue:@"" forHTTPHeaderField:@"timestamp"];
//    [self.requestSerializer setValue:@"" forHTTPHeaderField:@"nonce"];
//    [self.requestSerializer setValue:@"" forHTTPHeaderField:@"sign_version"];
//    [self.requestSerializer setValue:@"" forHTTPHeaderField:@"x_ca_key"];
//    [self.requestSerializer setValue:@"" forHTTPHeaderField:@"signature"];
}

//获取当前时间戳
+ (NSString *)currentTimeStr {
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}
//获取随机数
+ (NSString *)getArc4random {
    return [NSString stringWithFormat:@"%d",(arc4random() % 1000001) + 1000000];
}
// 加密算法
+ (NSString *)signature:(NSString *) time  AndRandom:(NSString *) random{
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:3];
    [dict setObject:time forKey:@"timestamp"];
    [dict setObject:random forKey:@"nonce"];
    [dict setObject:[LoginInfoHelper userId] forKey:@"user_id"];
    NSString *value = [self getNeedSignStrFrom:dict]; // key排序
    value = [self md5:value]; // md5加密
    value = [self takeFirst6AndLast8:value]; //取前6后8位反序
    value = [self md5:[self md5:value]]; // 两次md5加密
    return [value uppercaseString];
}
// 字典key排序
+ (NSString *)getNeedSignStrFrom:(id)obj{
    NSDictionary *dict = obj;
    NSArray *arrPrimary = dict.allKeys;
    
    NSArray *arrKey = [arrPrimary sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        NSComparisonResult result = [obj1 compare:obj2];
        return result==NSOrderedAscending;//NSOrderedAscending 倒序
    }];
    
    NSString*str =@"";
    for (NSString *s in arrKey) {
        id value = dict[s];
        if([value isKindOfClass:[NSDictionary class]]) {
            value = [self getNeedSignStrFrom:value];
        }
        if([str length] !=0) {
            
            str = [str stringByAppendingString:@"&"];
            
        }
        str = [str stringByAppendingFormat:@"%@",value];
    }
    
    return str;
}
// md5加密
+ (NSString *)md5EncryptWithString:(NSString *)string{
    return [self md5:[NSString stringWithFormat:@"%@%@", encryptionKey, string]];
}

+ (NSString *)md5:(NSString *)string{
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02X", digest[i]];
    }
    return  [result lowercaseString];
}
// 取前6后8 反序
+ (NSString *) takeFirst6AndLast8 :(NSString *) str {
    NSString * first6 = [str substringToIndex:6];
    NSString * last8 = [str substringFromIndex:str.length- 8];
    NSString * value = [NSString stringWithFormat:@"%@%@",first6,last8];
    value = [self inputValue:value];//反序
    return value;
}
//反序
+ (NSString *)inputValue:(NSString *) str {
    NSMutableString * string = [[NSMutableString alloc] init];
    for(int i = 0; i < str.length; i++){
        [string appendString:[str substringWithRange:NSMakeRange(str.length-i-1, 1)]];
    }
    return string;
}


/*-(NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method URLString:(NSString *)URLString parameters:(id)parameters headers:(NSDictionary<NSString *,NSString *> *)headers uploadProgress:(void (^)(NSProgress * _Nonnull))uploadProgress downloadProgress:(void (^)(NSProgress * _Nonnull))downloadProgress success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
    
    return [NSURLSessionTask new];
}
- (NSURLSessionDataTask *)addSignWithHTTPMethod:(NSString*)HttpMethod URLString:(NSString *)URLString
                       parameters:(nullable id)parameters
                          headers:(nullable NSDictionary <NSString *, NSString *> *)headers
                         progress:(nullable void (^)(NSProgress * _Nonnull))downloadProgress
                          success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
                      failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure{
    
//    return  self dataTaskWithHTTPMethod:HttpMethod URLString:URLString parameters:parameters headers:headers uploadProgress:<#^(NSProgress * _Nonnull)uploadProgress#> downloadProgress:<#^(NSProgress * _Nonnull)downloadProgress#> success:<#^(NSURLSessionDataTask * _Nonnull, id _Nullable)success#> failure:<#^(NSURLSessionDataTask * _Nullable, NSError * _Nonnull)failure#>
    
//
//    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters headers:headers uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure];
//    [dataTask resume];
//    return dataTask;
    
    
    
          
//    [AspectsTool zxl_AspectsWithClassName:@"AFHTTPSessionManager" Selector:@selector(dataTaskWithHTTPMethod:URLString:parameters:headers:uploadProgress:downloadProgress:success:failure:) Options:ZXLAspectPositionBefore UsingBlock:^(AspectsTool * _Nonnull info, NSError * _Nonnull error) {
//    
//        [self.requestSerializer setValue:@"" forHTTPHeaderField:@""];
//        
//        NSLog(@"appdelegate在走的类方法:instance == %@\narguments == %@\n", NSStringFromClass([info.zxl_instance class]),info.zxl_arguments);
//
//    }];
} */
@end
